package com.todod.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.mapper.CatalogDetailMapper;
import com.todod.model.CatalogDetail;
import com.todod.model.ProjectFile;
import com.todod.model.PublicFile;
import com.todod.service.ICatalogDetailService;
import com.todod.service.ProjectFileService;
import com.todod.service.PublicFileService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dyl
 * @date 2022-09-05
 */
@Service
@Transactional
public class CatalogDetailServiceImpl extends ServiceImpl<CatalogDetailMapper, CatalogDetail>
		implements ICatalogDetailService {
	@Autowired
	private CatalogDetailMapper catalogDetailMapper;
	@Autowired
	private PublicFileService publicFileService;
	@Autowired
	private ProjectFileService projectFileService;

	@Override
	public List<CatalogDetail> getListByUserIdAndType(Long _userId, Long classifyId) {
		List<CatalogDetail> returnList = new ArrayList<CatalogDetail>();

		List<String> names = new ArrayList<String>();

		QueryWrapper<CatalogDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("cmd_classify_id", classifyId);
		queryWrapper.eq("cmd_state", "1");
		queryWrapper.orderByAsc("cmd_sort_num");

		List<CatalogDetail> list = catalogDetailMapper.selectList(queryWrapper);
		for (CatalogDetail catalogDetail : list) {
			String levelParent = catalogDetail.getLevels();
			if (levelParent != null && StringUtils.isNotBlank(levelParent)) {
				String[] levelP = levelParent.split(",");
				if (levelP.length == 1) {
					if (!names.contains(catalogDetail.getId().toString())) {
						names.add(String.valueOf(catalogDetail.getId()));
						returnList.add(catalogDetail);
					}
				}
			} else {
				if (!names.contains(catalogDetail.getId().toString())) {
					names.add(String.valueOf(catalogDetail.getId()));
					returnList.add(catalogDetail);
				}
			}
		}

		return returnList;
	}

	@Override
	public List<CatalogDetail> getListByUserIdAndTypeAndParentId(Long _userId, Long parentId, String typeName) {
		List<CatalogDetail> returnList = new ArrayList<CatalogDetail>();

		List<String> names = new ArrayList<String>();

		QueryWrapper<CatalogDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("cmd_parent_id", parentId);

		if (typeName != null && StringUtils.isNotBlank(typeName)) {
			queryWrapper.eq("cmd_type_name", "%" + typeName + "%");
		}

		queryWrapper.eq("cmd_state", "1");
		queryWrapper.orderByAsc("cmd_sort_num");

		List<CatalogDetail> list = catalogDetailMapper.selectList(queryWrapper);
		for (CatalogDetail catalogDetail : list) {
			if (!names.contains(catalogDetail.getId().toString())) {
				names.add(String.valueOf(catalogDetail.getId()));
				returnList.add(catalogDetail);
			}
		}

		return returnList;
	}

	@Override
	public void saveData(Long _userId, CatalogDetail catalogDetail) {

		catalogDetail.setId(SnowflakeIdGenerator.getId());
		catalogDetail.setState("1");
		if (catalogDetail.getParentId() != 1) {
			CatalogDetail catalogDetail1 = catalogDetailMapper.selectById(catalogDetail.getParentId());
			if (catalogDetail1.getLevels() != null) {
				catalogDetail.setLevels(catalogDetail1.getLevels() + catalogDetail1.getId() + ",");
			} else {
				catalogDetail.setLevels(catalogDetail1.getId() + ",");
			}
		}

		catalogDetail.setCreatetimeTi(LocalDateTime.now());
		catalogDetail.setCreateuserId(_userId);

		catalogDetailMapper.insert(catalogDetail);
	}

	@Override
	public void editData(Long _userId, CatalogDetail catalogDetail) {

		CatalogDetail catalogDetail1 = catalogDetailMapper.selectById(catalogDetail.getId());

		catalogDetail.setCreatetimeTi(catalogDetail1.getCreatetimeTi());
		catalogDetail.setCreateuserId(catalogDetail1.getCreateuserId());
		catalogDetail.setModifytimeTi(LocalDateTime.now());
		catalogDetail.setModifyuserId(_userId);

		catalogDetailMapper.updateById(catalogDetail);
	}

	@Override
	public void copyData(Long _userId, CatalogDetail catalogDetail) {
		// 源数据
		CatalogDetail catalogDetailNew = catalogDetailMapper.selectById(catalogDetail.getId());

		Long cataLogId = catalogDetailNew.getId();
		// 在获取数据基础上，修改id、父id、排序、人员、时间
		catalogDetailNew.setId(SnowflakeIdGenerator.getId());
		catalogDetailNew.setParentId(catalogDetail.getParentId());
		Integer sortNum = catalogDetailMapper.getSortNumByDepartIdAndParentId(catalogDetailNew.getParentId());
		catalogDetailNew.setSortNum(sortNum);
		catalogDetailNew.setCreateuserId(_userId);
		catalogDetailNew.setCreatetimeTi(LocalDateTime.now());
		catalogDetailNew.setModifyuserId(_userId);
		catalogDetailNew.setModifytimeTi(LocalDateTime.now());

		// 源数据
		CatalogDetail catalogDetailNew1 = catalogDetailMapper.selectById(catalogDetail.getParentId());
		if (!catalogDetailNew1.getParentId().equals(1l)) {
			catalogDetailNew.setLevels(catalogDetailNew1.getLevels() + catalogDetail.getParentId() + ",");
		} else {
			catalogDetailNew.setLevels(catalogDetail.getParentId() + ",");
		}

		catalogDetailMapper.insert(catalogDetailNew);

		// 复制文件夹下面的文件夹和文件
		if (this.getListCatalogByParentId(cataLogId).size() > 0) {
			copyDataInChildren(_userId, cataLogId, catalogDetailNew.getId());
		}

	}

	/**
	 * @Title: copyDataInChildren
	 * @Description:复制文件夹及子文件数据
	 * @author: dyl
	 * @date 2022-09-05
	 * @param _userId
	 * @param catalogDetail
	 * @return
	 */
	public void copyDataInChildren(Long _userId, Long parentId, Long id) {
		List<CatalogDetail> listCatalog = this.getListCatalogByParentId(parentId);
		listCatalog.forEach(x -> {
			Long cataLogId = x.getId();

			x.setId(SnowflakeIdGenerator.getId());
			x.setParentId(id);
			Integer sortNum = catalogDetailMapper.getSortNumByDepartIdAndParentId(x.getParentId());
			x.setSortNum(sortNum);
			x.setCreateuserId(_userId);
			x.setCreatetimeTi(LocalDateTime.now());
			x.setModifyuserId(_userId);
			x.setModifytimeTi(LocalDateTime.now());

			// 源数据
			CatalogDetail catalogDetailNew1 = catalogDetailMapper.selectById(x.getParentId());
			if (catalogDetailNew1 != null) {
				if (!catalogDetailNew1.getParentId().equals(1l)) {
					x.setLevels(catalogDetailNew1.getLevels() + x.getParentId() + ",");
				} else {
					x.setLevels(x.getParentId() + ",");
				}
			}

			catalogDetailMapper.insert(x);

			if (this.getListCatalogByParentId(cataLogId).size() > 0) {
				copyDataInChildren(_userId, cataLogId, x.getId());
			}
		});
	}

	@Override
	public void moveData(Long _userId, CatalogDetail catalogDetail) {
		// 源数据
		CatalogDetail catalogDetailNew = catalogDetailMapper.selectById(catalogDetail.getId());
		// 在获取数据基础上，修改父id、排序、修改人员及时间
		catalogDetailNew.setParentId(catalogDetail.getParentId());
		Integer sortNum = catalogDetailMapper.getSortNumByDepartIdAndParentId(catalogDetailNew.getParentId());
		catalogDetailNew.setSortNum(sortNum);
		catalogDetailNew.setModifyuserId(_userId);
		catalogDetailNew.setModifytimeTi(LocalDateTime.now());

		// 源数据
		CatalogDetail catalogDetailNew1 = catalogDetailMapper.selectById(catalogDetail.getParentId());
		if (!catalogDetailNew1.getParentId().equals(1l)) {
			catalogDetailNew.setLevels(catalogDetailNew1.getLevels() + catalogDetail.getParentId() + ",");
		} else {
			catalogDetailNew.setLevels(catalogDetail.getParentId() + ",");
		}

		catalogDetailMapper.updateById(catalogDetailNew);
	}

	@Override
	public Map<String, Object> getChildren(Long parentId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CatalogDetail> listCatalog = this.getListCatalogByParentId(parentId);

		List<ProjectFile> listFile1 = projectFileService.getListFileByParentId(parentId);
		if (listFile1.size() > 0) {
			map.put("listFile2", listFile1);
		}
		if (listCatalog.size() > 0) {
			map.put("listCatalog", listCatalog);
			listCatalog.forEach(x -> {
				if (this.getListCatalogByParentId(x.getId()).size() > 0) {
					map.put("children", getChildren(x.getId()));
				}
			});
		}
		return map;
	}

	@Override
	public void deleteInLogic(Long _userId, Long id, String status) {
		// 源数据
//		CatalogDetail catalogDetailNew = catalogDetailMapper.selectById(id);
//		if (catalogDetailNew != null) {
//			catalogDetailNew.setState(status);
//			catalogDetailNew.setModifyuserId(_userId);
//			catalogDetailNew.setModifytimeTi(LocalDateTime.now());
//			catalogDetailMapper.updateById(catalogDetailNew);
//		}
		catalogDetailMapper.deleteById(id);
	}

	public void deleteIn(Long _userId, Long id, String status) {
		// 删除当前文件夹下面的文件夹和文件
		if (this.getListCatalogByParentId(id).size() > 0) {
			// 获取所有子节点
			Map<String, Object> map = getChildren(id);
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (entry.getKey().equalsIgnoreCase("listCatalog")) {
					List<CatalogDetail> listCatalog = (List<CatalogDetail>) entry.getValue();
					listCatalog.forEach(x -> {
						x.setState(status);
						x.setModifyuserId(_userId);
						x.setModifytimeTi(LocalDateTime.now());
					});
				}
			}
		}
	}

	private List<CatalogDetail> getListCatalogByParentId(Long parentId) {
		QueryWrapper<CatalogDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("cmd_parent_id", parentId);
		queryWrapper.eq("cmd_state", "1");
		queryWrapper.orderByAsc("cmd_sort_num");
		return catalogDetailMapper.selectList(queryWrapper);
	}

	@Override
	public Object getInfo(Long code) {
		Map<String, Object> map = new HashMap<>();
		CatalogDetail catalogDetail = catalogDetailMapper.getInfo(code);

		map.put("catalogDetail", catalogDetail);
		return map;
	}

	@Override
	public List<CatalogDetail> getTreeListInAuthority(Long classifyId) {
//		QueryWrapper<CatalogDetail> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("cmd_classify_id", classifyId);
//		queryWrapper.eq("cmd_state", "1");
//		queryWrapper.orderByAsc("cmd_sort_num");
//
//		List<CatalogDetail> list = catalogDetailMapper.selectList(queryWrapper);
		List<CatalogDetail> list = catalogDetailMapper.getTreeListInAuthority(classifyId);

		return list;
	}

	public Map<String, Object> getOnlyChildren(Long parentId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CatalogDetail> listCatalog = this.getListCatalogByParentId(parentId);
		listCatalog.forEach(x -> {
			if (this.getListCatalogByParentId(x.getId()).size() > 0
					|| publicFileService.getListFileByParentId(x.getId()).size() > 0) {
				map.put("children", getOnlyChildren(x.getId()));

			}

		});
		List<PublicFile> listFile = publicFileService.getListFileByParentId(parentId);
		if (listFile.size() > 0) {
			map.put("listFile", listFile);
		}
		return map;
	}

}
